<template>
  <div class="category-management">
    <!-- 筛选栏 -->
    <el-form :inline="true" :model="filters" class="filter-form">
      <el-form-item label="分类名称">
        <el-input v-model="filters.name" placeholder="请输入内容" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSearch">搜索</el-button>
        <el-button @click="onReset">重置</el-button>
        <el-button type="danger" @click="onCreate">新建分类</el-button>
      </el-form-item>
    </el-form>

    <!-- 分类树形表格 -->
    <el-table
      :data="pagedData"
      row-key="id"
      border
      style="width: 100%"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      default-expand-all="false"
    >
      <el-table-column prop="name" label="分类名称" />
      <el-table-column prop="order" label="排序" width="80" />
      <el-table-column prop="commission" label="品类佣金" width="120" />
      <el-table-column prop="status" label="状态" width="100" />
      <el-table-column label="操作" width="120">
        <template #default="scope">
          <el-button type="text" @click="onEdit(scope.row)">编辑</el-button>
          <el-button type="text" @click="onDelete(scope.row)" style="color: red"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-wrapper">
      <el-pagination
        background
        layout="prev, pager, next, jumper"
        :total="filteredData.length"
        :page-size="pageSize"
        :current-page.sync="currentPage"
        @current-change="onPageChange"
      />
    </div>

    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑分类' : '新建分类'"
    >
      <el-form :model="form" :rules="rules" ref="formRef">
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="排序" prop="order">
          <el-input-number v-model="form.order" :min="1" />
        </el-form-item>
        <el-form-item label="佣金" prop="commission">
          <el-input v-model="form.commission" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status">
            <el-option label="正常" value="正常" />
            <el-option label="禁用" value="禁用" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="onSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, nextTick } from "vue";
import { ElMessageBox, ElMessage } from "element-plus";

// mock分类数据
const allCategories = ref([
  {
    id: 1,
    name: "日化用品",
    order: 1,
    commission: "-",
    status: "正常",
    children: [
      { id: 11, name: "牙刷", order: 1, commission: "10%", status: "正常" },
    ],
  },
  { id: 2, name: "保健用品", order: 2, commission: "-", status: "正常" },
  { id: 3, name: "社区服务", order: 3, commission: "-", status: "正常" },
  { id: 4, name: "母婴用品", order: 4, commission: "-", status: "正常" },
  { id: 5, name: "食品饮料", order: 5, commission: "-", status: "正常" },
  { id: 6, name: "家用电器", order: 6, commission: "-", status: "正常" },
  { id: 7, name: "数码产品", order: 7, commission: "-", status: "正常" },
  { id: 8, name: "服装鞋帽", order: 8, commission: "-", status: "正常" },
  { id: 9, name: "家居家纺", order: 9, commission: "-", status: "正常" },
  { id: 10, name: "运动户外", order: 10, commission: "-", status: "正常" },
  { id: 12, name: "美妆个护", order: 11, commission: "-", status: "正常" },
  { id: 13, name: "汽车用品", order: 12, commission: "-", status: "正常" },
]);

const filters = ref({
  name: "",
});

const currentPage = ref(1);
const pageSize = 4;

// 展平树形数据用于分页
function flattenTree(tree) {
  const res = [];
  function dfs(nodes, parentExpanded = true) {
    for (const node of nodes) {
      res.push(node);
      if (node.children && node.children.length) {
        dfs(node.children, parentExpanded);
      }
    }
  }
  dfs(tree);
  return res;
}

const filteredData = computed(() => {
  let data = allCategories.value;
  if (filters.value.name) {
    // 只过滤一级分类和子分类名称
    data = data
      .map((cat) => {
        const match = cat.name.includes(filters.value.name);
        let children = cat.children || [];
        if (children.length) {
          children = children.filter((child) =>
            child.name.includes(filters.value.name)
          );
        }
        if (match || children.length) {
          return { ...cat, children: children.length ? children : undefined };
        }
        return null;
      })
      .filter(Boolean);
  }
  return data;
});

const pagedData = computed(() => {
  // 只对一级分类分页，子分类跟随父分类显示
  const start = (currentPage.value - 1) * pageSize;
  const end = start + pageSize;
  return filteredData.value.slice(start, end);
});

function onSearch() {
  currentPage.value = 1;
}
function onReset() {
  filters.value = { name: "" };
  currentPage.value = 1;
}
const dialogVisible = ref(false);
const isEdit = ref(false);
const form = ref({
  name: "",
  order: 1,
  commission: "",
  status: "正常",
  parentId: null,
});
const formRef = ref();
const rules = {
  name: [{ required: true, message: "请输入分类名称", trigger: "blur" }],
  order: [{ required: true, message: "请输入排序", trigger: "blur" }],
};

function onCreate(parent = null) {
  isEdit.value = false;
  form.value = {
    name: "",
    order: 1,
    commission: "",
    status: "正常",
    parentId: parent ? parent.id : null,
  };
  dialogVisible.value = true;
  nextTick(() => formRef.value && formRef.value.clearValidate());
}

function onEdit(row) {
  isEdit.value = true;
  form.value = { ...row, parentId: row.parentId || null };
  dialogVisible.value = true;
  nextTick(() => formRef.value && formRef.value.clearValidate());
}

function onSubmit() {
  formRef.value.validate().then(() => {
    if (isEdit.value) {
      // 编辑
      updateCategory(form.value);
    } else {
      // 新建
      addCategory(form.value);
    }
    dialogVisible.value = false;
  });
}

function addCategory(newCat) {
  // 只支持一级和二级
  if (newCat.parentId) {
    const parent = allCategories.value.find(
      (cat) => cat.id === newCat.parentId
    );
    if (parent) {
      const newId = Date.now();
      if (!parent.children) parent.children = [];
      parent.children.push({ ...newCat, id: newId });
      ElMessage.success("添加成功");
    }
  } else {
    allCategories.value.push({ ...newCat, id: Date.now() });
    ElMessage.success("添加成功");
  }
}

function updateCategory(editCat) {
  function update(nodes) {
    for (let i = 0; i < nodes.length; i++) {
      if (nodes[i].id === editCat.id) {
        nodes[i] = { ...nodes[i], ...editCat };
        return true;
      }
      if (nodes[i].children && update(nodes[i].children)) return true;
    }
    return false;
  }
  update(allCategories.value);
  ElMessage.success("编辑成功");
}

function onDelete(row) {
  ElMessageBox.confirm("确定要删除该分类吗？", "提示", {
    type: "warning",
  }).then(() => {
    function del(nodes) {
      for (let i = 0; i < nodes.length; i++) {
        if (nodes[i].id === row.id) {
          nodes.splice(i, 1);
          return true;
        }
        if (nodes[i].children && del(nodes[i].children)) return true;
      }
      return false;
    }
    del(allCategories.value);
    ElMessage.success("删除成功");
  });
}

function onPageChange(page) {
  currentPage.value = page;
}
</script>

<style scoped>
.category-management {
  padding: 24px;
}
.filter-form {
  margin-bottom: 16px;
}
.pagination-wrapper {
  margin-top: 16px;
  text-align: right;
}
</style>